package cn.linstudy.product.service.impl;

import cn.linstudy.common.utils.PageUtils;
import cn.linstudy.common.utils.Query;
import cn.linstudy.product.dao.CategoryDao;
import cn.linstudy.product.entity.CategoryEntity;
import cn.linstudy.product.service.CategoryBrandRelationService;
import cn.linstudy.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查询所有
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 找到所有一级分类
        List<CategoryEntity> collect = categoryEntities.stream().filter((categoryEntity) -> {
            // 返回父分类id为0的，父id等于0说明他是一级分类
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            // 设置子菜单
           menu.setChildren(getChildren(menu,categoryEntities));
           return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        // 设置每一个父分类的子分类
        return collect;
    }

    /**
     * 用showStatus状态来完成逻辑删除
     * @param asList id列表
     */
    @Override
    public void removeMenusByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatalogPath(Long catalogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catalogId, paths);
        // 他返回的是一个逆序的，需要再把他调整顺序
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        // 更新自己
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    private List<Long> findParentPath(Long catalogId , List<Long> paths){
        // 收集当前节点id
        paths.add(catalogId);
        CategoryEntity category = this.getById(catalogId);
        // 如果父id不为空，继续收集
        if (category.getParentCid() != 0 ){
            findParentPath(category.getParentCid(),paths);
        }
        return paths;
    }
    /**
     * 获取子菜单
     * @param currentMenu 当前菜单
     * @param allMenu 所有菜单
     * @return 所有子菜单
     */
    private List<CategoryEntity> getChildren(CategoryEntity currentMenu,List<CategoryEntity> allMenu){
        List<CategoryEntity> childrents = allMenu.stream().filter(categoryEntity -> categoryEntity.getParentCid() == currentMenu.getCatId())
                // 每个子菜单可能还有子菜单
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, allMenu));
                    return categoryEntity;
                })
                // 排序
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());;
        return childrents;

    }

}